package com.seguriapp.administration.gwt.server;

import java.util.LinkedHashMap;
import java.util.Map;

import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.DispatchException;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.restlet.resource.ClientResource;

import com.seguriapp.administration.gwt.shared.SaveUserDataAction;
import com.seguriapp.administration.gwt.shared.SaveUserDataResult;
import com.seguriapp.common.config.GlobalConfigLoader;
import com.seguriapp.common.gwt.server.AbstractSeguriAppHandler;
import com.seguriapp.util.Util;

public class SaveUserDataHandler  extends AbstractSeguriAppHandler<SaveUserDataAction, SaveUserDataResult> {

  private static final Logger LOGGER = Logger.getLogger(SaveUserDataHandler.class);

  public Class<SaveUserDataAction> getActionType() {
    return SaveUserDataAction.class;
  }

  public SaveUserDataResult execute(final SaveUserDataAction action, final ExecutionContext context) throws DispatchException {

    final SaveUserDataResult result = new SaveUserDataResult();
    try {
      final String url = GlobalConfigLoader.getInstance().getGlobalConfig().getBackEndUrl()
          .concat(GlobalConfigLoader.getInstance().getGlobalConfig().getSaveUserData());
      final ClientResource resource = new ClientResource(url);
      final String errorMessage = resource.post(convertDataToJsonString(action)).getText();
      result.setErrorMessage(errorMessage);
      LOGGER.info("Data received : \n" + errorMessage);
    } catch (Exception e) {
      LOGGER.error("Error saving user \n", e);
    }
    return result;
  }

  private String convertDataToJsonString(final SaveUserDataAction action) {
    final Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("username", action.getUser().getUsername());
    map.put("password", Util.encodeString(action.getUser().getPassword()));
    map.put("id", action.getUser().getId() == null ? 0 : action.getUser().getId());
    final JSONObject obj = new JSONObject();
    try {
      obj.put("userData", map);
    } catch (JSONException e) {
      LOGGER.error(e.getStackTrace());
    }
    LOGGER.info("Sending Data : \n" + obj.toString());
    return obj.toString();
  }

}
